<template>
  <ClientOnly>
    <div class="articles-page">
      <div class="container">
        <!-- 主内容区 -->
        <div class="main-content">
          <!-- 搜索和筛选区域 -->
          <div class="search-section">
            <div class="search-header">
              <h1 class="page-title">文章列表</h1>
              <p class="page-desc">
                共 <strong>{{ total }}</strong> 篇文章
              </p>
            </div>

            <!-- 搜索框 -->
            <div class="search-box">
              <a-input
                v-model:value="searchKeyword"
                placeholder="搜索文章标题、内容（按 Enter 键搜索）"
                allow-clear
                @press-enter="handleSearch"
              >
                <template #prefix>
                  <IconSearch style="width: 18px; height: 18px; color: #a0aec0" />
                </template>
              </a-input>
            </div>

            <!-- 标签筛选 -->
            <div class="tags-filter">
              <div class="filter-label">
                <IconTag class="icon" />
                <span>按标签筛选：</span>
              </div>
              <div class="tags-list">
                <span
                  class="tag-filter-item"
                  :class="{ active: selectedTag === '' }"
                  @click="handleTagChange('')"
                >
                  全部
                </span>
                <span
                  v-for="tag in allTags"
                  :key="tag.id"
                  class="tag-filter-item"
                  :class="{ active: selectedTag === tag.id.toString() }"
                  @click="handleTagChange(tag.id.toString())"
                >
                  {{ tag.name }}
                </span>
              </div>
            </div>
          </div>

          <!-- 文章列表 -->
          <div v-if="allArticles.length > 0" class="articles-list">
            <article
              v-for="article in allArticles"
              :key="article.id"
              class="article-item"
              @click="navigateTo(`/article/${article.id}`)"
            >
              <div class="article-cover">
                <img :src="renderCoverImg(article)" :alt="article.title" />
                <span
                  v-for="value in article?.categoryId?.split(',')"
                  :key="value"
                  class="article-category"
                  >{{ _hotTags.find((tag: any) => +tag.id === +value)?.name }}</span
                >
              </div>
              <div class="article-info">
                <h3 class="article-title">{{ article.title }}</h3>
                <p class="article-excerpt">{{ article.content }}</p>
                <div class="article-tags">
                  <a-tag
                    v-for="tag in article.categoryId.split(',')"
                    :key="tag"
                    color="purple"
                    class="article-tag"
                  >
                    {{ _hotTags.find((item: any) => +tag === +item.id)?.name }}
                  </a-tag>
                </div>
                <div class="article-meta">
                  <div class="author-info">
                    <img :src="headerImg" alt="作者" class="avatar" />
                    <span class="author-name">@秋水无痕</span>
                    <span class="separator">•</span>
                    <span class="date">{{ dayjs(article.updateTime).format('MM/DD/YYYY') }}</span>
                  </div>
                  <div class="stats">
                    <span class="stat-item">
                      <EyeFilled />
                      {{ article.readCounts }}
                    </span>
                    <span class="stat-item">
                      <HeartFilled />
                      {{ article.favoriteCount }}
                    </span>
                    <span class="stat-item">
                      <LikeFilled />
                      {{ article.likeCount }}
                    </span>
                  </div>
                </div>
              </div>
            </article>
          </div>

          <!-- 空状态 -->
          <EmptyState
            v-else
            title="未找到相关文章"
            description="试试其他关键词或标签吧"
            button-text="清空筛选"
            @button-click="clearAllFilters"
          >
            <template #icon>
              <div class="empty-icon">🔍</div>
            </template>
          </EmptyState>

          <!-- 分页 -->
          <div v-if="allArticles.length > 0" class="pagination">
            <a-pagination
              v-model:current="currentPage"
              :total="total"
              :page-size="pageSize"
              show-size-changer
              show-quick-jumper
              :show-total="(total: number) => `共 ${total} 篇文章`"
              @change="handlePageChange"
            />
          </div>
        </div>

        <!-- 右侧边栏 -->
        <AppSidebar :selected-tag="selectedTag" @tag-click="handleTagChange" />
      </div>
    </div>
  </ClientOnly>
</template>

<script setup lang="ts">
import { EyeFilled, HeartFilled, LikeFilled } from '@ant-design/icons-vue'
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import IconSearch from '~/assets/icons/IconSearch.vue'
import IconTag from '~/assets/icons/IconTag.vue'
import AppSidebar from '~/components/AppSidebar.vue'
import { getArticleListClient, getTagsList } from '~/api/article'
import dayjs from 'dayjs'
import defaultImg from '@/assets/image/default.jpg'
import headerImg from '@/assets/image/header.png'
import storage from '@/utils/storage'
// 热门标签
const _hotTags = ref<any>([])
// 渲染背景图片
const renderCoverImg = (article: any) => {
  if (article.articleCover) {
    return article.articleCover
  }
  return defaultImg
}
// 所有可用标签
const allTags = ref<any[]>(storage.get('hotTags') || [])

// 获取路由参数
const route = useRoute()

// 搜索和筛选状态
const searchKeyword = ref('')
const selectedTag = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 模拟文章数据
const allArticles = ref<any[]>([])

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  getArticleList()
}

// 处理标签变化
const handleTagChange = (tagId: string) => {
  // 防止重复点击相同标签导致闪烁
  if (selectedTag.value === tagId) {
    return
  }
  selectedTag.value = tagId
  currentPage.value = 1
  getArticleList()
}

// 清空所有筛选
const clearAllFilters = () => {
  searchKeyword.value = ''
  selectedTag.value = ''
  currentPage.value = 1
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 获取文章列表
const getArticleList = () => {
  getArticleListClient({
    page: currentPage.value,
    size: pageSize.value,
    categoryId: selectedTag.value,
    title: searchKeyword.value,
  }).then((result: any) => {
    if (result.code === 200) {
      allArticles.value = result.data.list
      total.value = result.data.count
    }
  })
}

// 监听路由参数变化
watch(
  () => route.query.categoryId,
  (newCategoryId) => {
    if (newCategoryId) {
      selectedTag.value = newCategoryId as string
      currentPage.value = 1
      getArticleList()
    }
  },
  { immediate: true },
)

onMounted(() => {
  getArticleList()
})
// SEO
useHead({
  title: '文章列表 - 鹿鸣博客',
  meta: [{ name: 'description', content: '浏览所有技术文章，涵盖前端、后端、运维等多个领域' }],
})
</script>

<style scoped>
.articles-page {
  /* background: #f7fafc; */
  /* min-height: 100vh; */
  padding: 24px 0;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
  display: flex;
  gap: 24px;
}

/* 主内容区 */
.main-content {
  flex: 1;
  max-width: calc(100% - 344px);
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.search-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  color: #1a202c;
  margin: 0 0 8px 0;
}

.page-desc {
  font-size: 14px;
  color: #718096;
  margin: 0;
}

.page-desc strong {
  color: #667eea;
  font-weight: 700;
}

.search-box {
  margin-bottom: 24px;
}

.search-box :deep(.ant-input-affix-wrapper) {
  border-radius: 8px;
  border: 2px solid #e2e8f0;
  padding: 10px 14px;
  font-size: 14px;
  transition: all 0.3s;
}

.search-box :deep(.ant-input-affix-wrapper:hover) {
  border-color: #cbd5e0;
}

.search-box :deep(.ant-input-affix-wrapper:focus),
.search-box :deep(.ant-input-affix-wrapper-focused) {
  border-color: #667eea !important;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1) !important;
  outline: none !important;
}

.search-box :deep(.ant-input:focus) {
  box-shadow: none !important;
}

/* 标签筛选 */
.tags-filter {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 20px;
  background: #f7fafc;
  border-radius: 8px;
}

.filter-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #4a5568;
  white-space: nowrap;
  padding-top: 4px;
}

.filter-label .icon {
  width: 16px;
  height: 16px;
  color: #667eea;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-filter-item {
  padding: 8px 16px;
  background: #f7fafc;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #4a5568;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  will-change: transform;
}

.tag-filter-item:hover {
  border-color: #667eea;
  color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
}

.tag-filter-item.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
  color: white;
  font-weight: 600;
  transform: translateY(0);
}

.tag-filter-item.active:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 筛选状态 */
.filter-status {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 16px;
  padding: 12px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  border-radius: 8px;
}

.status-text {
  font-size: 13px;
  color: #4a5568;
  font-weight: 600;
}

/* 文章列表 */
.articles-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.article-item {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  gap: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  cursor: pointer;
}

.article-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.article-cover {
  position: relative;
  width: 240px;
  height: 160px;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
}

.article-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.article-item:hover .article-cover img {
  transform: scale(1.1);
}

.article-category {
  position: absolute;
  top: 12px;
  left: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.article-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.article-title {
  font-size: 20px;
  font-weight: 700;
  color: #1a202c;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

.article-excerpt {
  font-size: 14px;
  color: #718096;
  line-height: 1.6;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 12px;
}

.article-tag {
  font-size: 12px;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #a0aec0;
}

.avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.author-name {
  font-weight: 600;
  color: #4a5568;
}

.separator {
  color: #cbd5e0;
}

.stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #a0aec0;
}

.stat-item .icon {
  width: 16px;
  height: 16px;
}

/* 空状态 */
.empty-state {
  background: white;
  border-radius: 12px;
  padding: 80px 40px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-state h3 {
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
  margin: 0 0 8px 0;
}

.empty-state p {
  font-size: 14px;
  color: #718096;
  margin: 0 0 24px 0;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 响应式 */
@media (max-width: 968px) {
  .container {
    flex-direction: column;
  }

  .main-content {
    max-width: 100%;
  }

  .tags-filter {
    flex-direction: column;
    align-items: flex-start;
  }

  .article-item {
    flex-direction: column;
  }

  .article-cover {
    width: 100%;
    height: 200px;
  }
}
</style>
